<style scoped>
.whitebg {
  background-color: #fff;
}
.tit {
  font-size: 16px;
}
</style>


<template>
  <div class="mb30">
    <h2 class="form-tit-row lineb whitebg tit">{{title}}
      <span v-if="max > 0">最多可上传{{max}}张</span>
    </h2>
    <div class="form-wrap">
      <div class="form-wrap-row"
           v-if="max === 0 && imgList.length === 0">
        暂无图片
      </div>
      <div class="form-wrap-row"
           v-else>
        <ul class="pic-list cf">
          <li v-for="(item,index) in imgListBd">
            <img :src="item"
                 @click="showPrevimg(index)"
                 v-if="item.indexOf('base64') > -1">
            <img :src="item"
                 @click="showPrevimg(index)"
                 v-else>
            <i class="iconfont icon-del-black"
               @click="delImage(index)"
               v-if="max > 0"></i>
          </li>
          <div class="upload-btn"
               @click="getFlag()"
               v-if="max > 0">
            <i class="iconfont icon-add"></i>
          </div>
        </ul>
      </div>
    </div>
    <previewer ref="previewer"
               :list="previewerList"
               :options="options"></previewer>
    <!-- <viewer :show-prev='showPrev' :prev-item='prevItem' v-on:close="closeViewer()"></viewer> -->
  </div>
</template>

<script>
import { Previewer } from 'vux';
import viewer from "@/components/share/ImageUploader/viewer.vue";
export default {
  components: {
    Previewer
  },
  props: {
    title: {
      type: String,
      required: true,
      default: '拍照或选择图片'
    },
    imgList: {
      type: Array,
      required: true,
      default: [],
    },
    imgListBd: {
      type: Array,
      required: true,
      default: [],
    },
    max: {
      type: Number,
      required: true,
      default: 9,
    }
  },
  data () {
    return {
      showPrev: false,
      prevItem: {},
      filter: this.$options.filters,
      previewerList: [],
      options: {
        isClickableElement: function (el) {
          return /previewer-delete-icon/.test(el.className)
        }
      }
    }
  },
  created () {
    this.sortPrevimg();
  },
  watch: {
    imgList: {
      handler (newName, oldName) {
        this.sortPrevimg();
      },
      deep: true,
    }
  },
  methods: {
    sortPrevimg () {
      let args = [];
      if (this.imgList.length > 0) {
        this.imgList.forEach(x => {
          let item = {};
          if (x.indexOf('base64') > -1) {
            item = {
              src: x
            }
          } else {
            item = {
              src: this.filter['simpleImgUrl'](x)
            }
          }
          args.push(item);
        });
        this.previewerList = args;
      }
    },
    showPrevimg (index) {
      this.$refs.previewer.show(index);
    },

    PrevPic (item) {
      if (item.indexOf('base64') > -1) {
        this.prevItem = { Base64: item };
      } else {
        this.prevItem = { Url: item };
      }
      this.showPrev = !this.showPrev;
    },

    delImage (i, filename) {
      var self = this;
      var query = [];
      self.imgList.splice(i, 1);
      query.push(filename);
      self.imgListBd.splice(i, 1);
      // self.Ajax.postloadDelImg("/ms-common-admin-cloud-service/obs/del-image", query).then(function (resp) {
      //   console.log(resp);
      //   if (resp.msg == 'success') {


      //   }
      // });
    },

    testgetFlag () {
      this.imgList.push("")
    },

    getFlag () {
      var self = this;
      let currentSize = this.imgList.length;

      if (currentSize >= this.max) {
        self.Toast({
          message: `最多只能上传${this.max}张图片！`,
        });
        return false;
      }

      this.jWeixin.chooseImage({
        count: self.max - currentSize, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          var localIds = res.localIds;
          console.log(localIds, 'localIds');
          // if (self.imgList.length + localIds.length > self.max) {
          //   self.Toast({
          //     message: `最多只能上传${self.max}张图片！`,
          //   });
          //   return false;
          // } else {
          //   localIds.forEach((x) => {
          //     self.imgList.push(x);
          //   });
          //   self.getLocalImgData(currentSize);
          // }
        }
      });
    },
    getLocalImgData: function (i) {
      var self = this;
      this.jWeixin.getLocalImgData({
        localId: self.imgList[i], // 图片的localID
        success: function (resTwo) {
          console.log(resTwo.localData);//打印获取到的图片base64码
          if (resTwo.localData.indexOf(";base64,") == -1) {//兼容处理，安卓获取的图片base64码没有前缀，而苹果有,base64前缀并不固定
            resTwo.localData = "data:image/jpeg;base64," + resTwo.localData;//加上base64前缀
          }
          if (resTwo.localData.indexOf("data:image/jgp;base64,") != -1) {//兼容处理，若是苹果手机，将前缀中的jgp替换成jpeg
            resTwo.localData = resTwo.localData.replace("data:image/jgp;base64,", "data:image/jpeg;base64,");
          }
          var imgbase64 = '';
          //这样计算出来的图片大小与图片实际大小有一定差别，一般会比原图大30%的样子，猜测可能是wx.chooseImage导致图片变大了。不过大体能用
          console.log("图片大小：" + resTwo.localData.length / 1024 / 1.3 + "KB");//打印计算出来的图片大小
          //计算压缩比例（按压缩到100kb计算）：压缩比例 = (图片大小/100)再开根号再取整
          //由于开跟、取整等操作，压缩比例存在一定偏差，但是大体能用
          var prop = parseInt(Math.sqrt(resTwo.localData.length / 102400 / 1.3));
          console.log(prop);//打印压缩比例
          if (prop > 1) {//若图片>100kb，即压缩比例>1，压缩图片
            imgbase64 = self.compressedImg(resTwo.localData, prop);//使用canvas压缩图片
          } else {//否则，可以直接使用该图片
            imgbase64 = resTwo.localData;
            console.log(resTwo.localData);
          }
          var imglistData = [];
          imglistData.push(imgbase64.split(',')[1]);
          var query = {
            imgList: imglistData
          }
          console.log(query);
          self.Ajax.postload("GetPictUploadContent", query, '正在上传第' + (i + 1) + '张图片....').then(function (resp) {
            console.log(resp);
            if (resp.IsSuccess) {
              var path = decodeURIComponent(resp.Data);
              var pathData = path.split('/');
              //var filename = pathData[pathData.length - 1];
              var Img = {
                fileName: pathData[pathData.length - 1],
                path: decodeURIComponent(resp.Data)
              }
              self.imgListBd.push(path);

              self.imgList.splice(i, 1, localData);
              self.getLocalImgData(i + 1);
              console.log(self.imgListBd);
            } else {

            }
          });
        }
      });
    },
    closeViewer () {
      this.showPrev = false;
      this.prevItem = {};
    },
    //获取base64图片大小，返回kb数字
    showSize (base64url) {
      //把头部去掉
      var str = base64url;//base64url.replace('data:image/png;base64,', '');
      // 找到等号，把等号也去掉
      var equalIndex = str.indexOf('=');
      if (str.indexOf('=') > 0) {
        str = str.substring(0, equalIndex);
      }
      // 原来的字符流大小，单位为字节
      var strLength = str.length;
      // 计算后得到的文件流大小，单位为字节
      var fileLength = parseInt(strLength - (strLength / 8) * 2);
      // 由字节转换为kb
      var size = "";
      size = (fileLength / 1024).toFixed(2);
      var sizeStr = size + ""; //转成字符串
      var index = sizeStr.indexOf("."); //获取小数点处的索引
      var dou = sizeStr.substr(index + 1, 2) //获取小数点后两位的值
      if (dou == "00") { //判断后两位是否为00，如果是则删除00                
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
      }
      return size / 1024;
    },
    compressedImg (path, prop) {
      var base64img = '';
      var img = new Image();
      img.src = path;
      img.onload = function () {
        var that = this;
        // 按压缩比例进行压缩
        var w = that.width / prop,
          h = that.height / prop;
        // console.log(w);
        // console.log(h);
        var quality = 1;  // 默认图片质量为1
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        // quality值越小，所绘制出的图像越模糊
        var imgUrl = canvas.toDataURL('image/jpeg', quality);//压缩后的图片base64码
        base64img = imgUrl;
        console.log(imgUrl);//打印压缩后的图片base64码
        console.log("压缩后：" + imgUrl.length / 1024 + "KB");
        //return imgUrl;
      }
      return base64img;
    }
  }
}
</script>